//
// Created by sgyt on 2020/4/26.
// 线程和信号

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
//阻塞信号集
sigset_t mask;
sigset_t old_mask;

//互斥锁
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitlock = PTHREAD_COND_INITIALIZER;

//设置线程0
int quitflag;

void *pthread_fun(void *arg);

int main(int argc,char *argv[])
{
    pthread_t p1;
    int res;

    //初始化阻塞信号集
    sigemptyset(&mask);
    sigaddset(&mask,SIGINT);
    sigaddset(&mask,SIGQUIT);

    //设置线程阻塞信号
    res = pthread_sigmask(SIG_BLOCK,&mask,&old_mask);
    if(res != 0)
    {
        perror("pthread_sigmask is error\n");
    }

    //创建线程
    pthread_create(&p1,NULL,pthread_fun,NULL);

    //锁住
    pthread_mutex_lock(&lock);
    while(quitflag == 0)
    {
        pthread_cond_wait(&waitlock,&lock);
    }
    pthread_mutex_unlock(&lock);

    //线程等待
    pthread_join(p1,NULL);

    //主线程结束
    printf("main process is finish\n");

    return 0;
}

void *pthread_fun(void *arg){
    //设置屏蔽信号
    int err,signo;

    for(;;)
    {
        err = sigwait(&mask,&signo);

        if(err != 0)
        {
            perror("sigwait is error\n");
        }

        switch (signo){
            case SIGINT:
                printf("\ninterrupt\n");
                break;
            case SIGQUIT:
                pthread_mutex_lock(&lock);
                quitflag = 1;
                pthread_mutex_unlock(&lock);
                pthread_cond_signal(&waitlock);
                return 0;
            default:
                printf("unexpected signal %d\n",signo);
                exit(1);
        }
    }

}

